// app/service/dashboard.js
const { Service } = require('egg');

class DashboardService extends Service {
  /**
   * 获取供应商统计数据
   * @param {string} provinceCode - 省份代码
   * @returns {Promise<Array>} 统计结果
   */
  async getSupplierStats(provinceCode) {
    // 参数校验
    this._validateProvinceCode(provinceCode);

    // 尝试从缓存获取
    const cacheKey = `supplier_stats:${provinceCode}`;
    const cachedData = await this.app.redis.get(cacheKey);

    if (cachedData) {
      this.logger.info(`[DashboardService] 从缓存获取${provinceCode}供应商统计数据`);
      return JSON.parse(cachedData);
    }

    // 缓存未命中，从数据库获取并缓存
    return await this._getAndCacheSupplierStats(provinceCode, cacheKey);
  }

  /**
   * 验证省份代码合法性
   * @private
   * @param {string} provinceCode - 省份代码
   */
  _validateProvinceCode(provinceCode) {
    const { app } = this;
    // 政采云省份代码规则：2位字母或6位数字
    const provinceCodeRule = /^([A-Z]{2}|\d{6})$/;

    if (!provinceCode || !provinceCodeRule.test(provinceCode)) {
      this.logger.warn(`[DashboardService] 无效的省份代码: ${provinceCode}`);
      throw new app.errors.ValidationError('无效的省份代码', {
        field: 'provinceCode',
        value: provinceCode,
        rule: '必须是2位字母或6位数字'
      });
    }

    // 验证省份代码是否在系统配置列表中
    const validProvinces = app.config.zcyConfig.provinceCodes || [];
    if (validProvinces.length > 0 && !validProvinces.includes(provinceCode)) {
      this.logger.warn(`[DashboardService] 省份代码不在授权列表中: ${provinceCode}`);
      throw new app.errors.AuthorizationError('省份代码不在授权列表中', {
        field: 'provinceCode',
        value: provinceCode
      });
    }
  }

  /**
   * 从数据库获取并缓存供应商统计数据
   * @private
   * @param {string} provinceCode - 省份代码
   * @param {string} cacheKey - 缓存键
   * @returns {Promise<Array>} 统计结果
   */
  async _getAndCacheSupplierStats(provinceCode, cacheKey) {
    const { Supplier } = this.ctx.model;
    const Op = this.app.Sequelize.Op;

    this.logger.info(`[DashboardService] 从数据库获取${provinceCode}供应商统计数据`);

    try {
      const result = await Supplier.findAll({
        attributes: [
          'risk_level',
          [this.app.Sequelize.fn('COUNT', this.app.Sequelize.col('id')), 'count'],
          [this.app.Sequelize.fn('AVG', this.app.Sequelize.col('response_time')), 'avg_response']
        ],
        where: {
          province_code: provinceCode,
          // 只统计有效供应商
          is_deleted: { [Op.eq]: false }
        },
        group: ['risk_level'],
        order: [[ 'risk_level', 'ASC' ]],
        raw: true
      });

      // 缓存结果，设置20分钟过期
      await this.app.redis.set(cacheKey, JSON.stringify(result), 'EX', 1200);
      this.logger.info(`[DashboardService] 缓存${provinceCode}供应商统计数据成功`);

      return result;
    } catch (error) {
      this.logger.error(`[DashboardService] 获取供应商统计数据失败: ${error.message}`, error);
      throw new Error(`获取供应商统计数据失败: ${error.message}`);
    }
  }
}